<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta http-equiv="X-UA-Compatible" content="ie=edge"/>
    <title></title>

    <script src="../js/vue.global.js"></script>
    <!--<script src="../../imap_jw/js/vue.js" type="text/javascript"></script>-->
    <!--   <script src="js/test.js" type="text/javascript" charset="utf-8"></script>-->
    <link href="../css/imap-gl.css" rel="stylesheet"/>
    <script src="../js/imap-gl.js"></script>
</head>
<style type="text/css">
    #app {
        position: absolute;
        width: 100vw;
        height: 100vh;
        left: 0;
        top: 0;
        margin: 0;
        padding: 0;
    }

    .map_contaner {
        width: 100%;
        height: 100%;
        position: absolute;
    }

    .evenDiv {
        position: absolute;
        top: 15px;
        left: 15px;
        background-color: #ffffff;
        border-radius: 2px;
        width: 380px;
        padding: 10px;
        box-sizing: border-box;
        box-shadow: 1px 2px 1px rgba(0, 0, 0, 0.15);
        font-size: 13px;
    }

    .showData {
        position: relative;
        top: 77px;
        left: 15px;
        background-color: #44b79d;
        border-radius: 2px;
        width: 380px;
        padding: 10px;
        box-sizing: border-box;
        box-shadow: 1px 2px 1px rgba(0, 0, 0, 0.15);
        font-size: 13px;
    }
    .showData>table{     width: 100%;}

    .evenDiv > table {
        width: 100%;
    }

    .evenDiv > table tr {
        line-height: 35px;
    }

    .evenDiv > table input {
        border: none;
    }

    .evenDiv > table input:focus {
        border: none;
        outline: none;
    }

    .search-btn {
        width: 70px;
        height: 25px;
        line-height: 25px;
        text-align: center;

        margin-left: auto;
        color: #FFF;
        background-color: #44b79d;
        cursor: pointer;
        position: relative;
        border-radius: 2px;
        box-sizing: border-box;
        box-shadow: 1px 2px 1px rgba(0, 0, 0, 0.15);
    }

    .search-link {
        width: 70px;
        height: 25px;
        line-height: 25px;
        text-align: center;

        color: #44b79d;
        cursor: pointer;
        position: absolute;
        border-radius: 2px;
    }
</style>

<body>
<div id="app">

</div>
</body>


<script type="text/javascript">
    const wsServer = "ws://192.168.11.39:8088";
    Vue.createApp({
        data() {
            return {
                msg: "vue",
                routeArr: [],
                socket: null,
                lnglat: [],
                isTest: [2, 4],
                carLocaltion: [],
                searchBtnState: -1,
                navLineInfo: {
                    CurRoadName: 0,
                    NextRoadName: "",
                    Icon: "",
                    RouteRemainDis: 0,
                    RouteRemainTime: 0,
                    SegRemainDis: 0,
                    CarDirection: 0
                }
            }
        },
        methods: {
            initMap() {
                //加载地图
                //imapgl.msp_server = "http://api.ishowchina.com";
                imapgl.workerCount = 6; //获取并设置在带有GL JS映射的页面上实例化的Web Worker的数量。默认情况下，它设置为CPU内核数的一半（上限为6）。
                imapgl.maxParallelImageRequests = 5; //获取并设置要并行加载的最大图像数量（栅格图块，子画面，图标）
                // imapgl.baseApiUrl = 'http://172.192.100.51:54321/';
                this.map = new imapgl.Map({
                    container: 'map',
                    center: [116.27771321722543, 39.952128183377255],
                    zoom: 12,
                    minZoom: 3,
                    maxZoom: 20,
                    hash: false,
                    antialias: false,
                    style: 'http://172.192.100.51:50001/imap_jw/styles/v1/light-v10-gcj02-lc.json'
                });
                let that = this;
                this.map.on("click", function (e) {
                    if (that.lnglat.length > 2) {
                        that.map["marker_red"] && that.map["marker_red"].remove();
                        that.map["marker_blue"] && that.map["marker_blue"].remove();
                        that.lnglat = []
                    }
                    that.lnglat.push(e.lngLat);
                    if (that.lnglat.length == 1)that.addMarker("marker_blue")
                    if (that.lnglat.length == 2)that.addMarker("marker_red")
                    //console.log(that.lnglat)
                    if (that.lnglat.length == 2)that.searchBtnState = 0;
                });
                this.map.on("pitchend", function (e) {
                    if (this.carDiv) {
                        let d = (this.map.getPitch())
                        this.carDiv.style.cssText = "transform-style: preserve-3d;transform: rotateX(-{0}deg);".replace("{0}", d)
                    }
                })
            },
            addMarker(type){

                let marker_red = document.createElement("div")
                marker_red.style.cssText = "width:30px;height:30px";
                marker_red.innerHTML = "<svg t='1594346569381' class='icon' viewBox='0 0 1024 1024' version='1.1' xmlns='http://www.w3.org/2000/svg' p-id='6357' width='32' height='32' xmlns:xlink='http://www.w3.org/1999/xlink'><defs><style type='text/css'></style></defs><path d='M512 0C345.975467 0 152.234667 101.444267 152.234667 359.765333c0 175.3088 276.753067 562.7904 359.765333 664.234667 73.796267-101.444267 359.765333-479.709867 359.765333-664.234667C871.765333 101.512533 678.024533 0 512 0z' p-id='6358' fill='#E8371B'></path></svg><div style='position: absolute;position: absolute;left: 9.3px;top: 3px;font-size: 14px;color: #ffffff;'>终</div>"
                let marker_blue = document.createElement("div")
                marker_blue.style.cssText = "width:30px;height:30px";
                marker_blue.innerHTML = "<svg t='1594346569381' class='icon' viewBox='0 0 1024 1024' version='1.1' xmlns='http://www.w3.org/2000/svg' p-id='6357' width='32' height='32' xmlns:xlink='http://www.w3.org/1999/xlink'><defs><style type='text/css'></style></defs><path d='M512 0C345.975467 0 152.234667 101.444267 152.234667 359.765333c0 175.3088 276.753067 562.7904 359.765333 664.234667 73.796267-101.444267 359.765333-479.709867 359.765333-664.234667C871.765333 101.512533 678.024533 0 512 0z' p-id='6358' fill='#398CF3'></path></svg><div style='position: absolute;position: absolute;left: 9.3px;top: 3px;font-size: 14px;color: #ffffff;'>起</div>"

                if (type == "marker_red") {
                    let m = this.lnglat[1]
                    this.map[type] = new imapgl.Marker(marker_red).setLngLat([Number(m.lng), Number(m.lat)]).addTo(this.map);
                }
                if (type == "marker_blue") {
                    let m = this.lnglat[0]
                    this.map[type] = new imapgl.Marker(marker_blue).setLngLat([Number(m.lng), Number(m.lat)]).addTo(this.map);
                }
            },
            initWebsocket() {
                if (window.WebSocket) {
                    //实例化
                    this.socket = new WebSocket(wsServer);
                    //监听连接
                    this.socket.onopen = this.open;
                    //监听报错
                    this.socket.onerror = this.error;
                    //监听返回信息
                    this.socket.onmessage = this.getMessage;
                    //监听关闭
                    this.socket.onclose = this.close;
                }
            },
            open() {
                console.log("连接成功")
            },
            error() {
                console.log("连接失败")
            },
            getMessage(data) {
                let curData = JSON.parse(data.data);
                //console.log(data)
                switch (curData.FunctionName) {
                    //算路数据
                    case "requestRoute":
                        this.routeArr = curData.ReturnValue.RouteCoors;
                        //console.log(this.routeArr)
                        let curArr = this.routeArr;
                        let oldArr = [], newArr = [];
                        for (var i = 0; i < curArr.length; i++) {
                            let oldCoord = Number(curArr[i].Longitude) + ',' + Number(curArr[i].latitude);
                            oldArr.push(oldCoord);
                        }
                        if (oldArr) {
                            for (var j = 0; j < oldArr.length; j++) {
                                let curArr = oldArr[j].split(",");
                                curArr[0] = Number(curArr[0])
                                curArr[1] = Number(curArr[1])
                                newArr.push(curArr)
                            }
                        }
                        //算路数据绘制
                        this.drawLine(newArr)

                        //视野设置
                        this.setBounds(newArr)

                        this.searchBtnState = 1;
                        break;
                    //导航位置数据
                    case "updateNaviInfo":
                        //无导航不更新
                        let BaseNaviInfo = curData.Parameter.BaseNaviInfo;
                        this.carLocaltion = [Number(BaseNaviInfo.Longitude), Number(BaseNaviInfo.Latitude)];
                        if (this.searchBtnState == 2) {
                            this.updateNaviInfo(curData)
                        }
                        break;
                    //获取car的当前位置
                    case "updateLaneInfo":
                        let ShowLaneInfo = curData.Parameter;
                            console.log(ShowLaneInfo)
                        break;
                }
            },
            updateNaviInfo(curData){
                console.log(this.carLocaltion)
                let CarDirection = curData.Parameter.BaseNaviInfo.CarDirection;
                //赋值
                this.navLineInfo = curData.Parameter.BaseNaviInfo
                //小车的位置变化
                if (this.carLng)this.carLng.setLngLat(this.carLocaltion);
                this.map.easeTo({
                    pitch: 60,
                    bearing: Number(CarDirection),
                    center: this.carLocaltion,
                    zoom: 16,
                    easing: function (t) {
                        return t * (2 - t)
                    }
                });
            },
            setBounds(lnglat){
                const xx = [], yy = []
                lnglat.map(function (a) {
                    xx.push(a[0]);
                    yy.push(a[1]);
                });
                xx.sort()
                yy.sort()
                let bbox = [
                    [Number(xx[0]), Number(yy[0])],
                    [Number(xx[xx.length - 1]), Number(yy[yy.length - 1])]
                ];
                this.map.fitBounds(bbox, {
                    padding: {
                        top: 250,
                        bottom: 50,
                        left: 350,
                        right: 50
                    }
                });
                this.map.easeTo({
                    pitch: 0,
                    bearing: 0,
                    easing: function (t) {
                        return t * (2 - t)
                    }
                });
            },
            send(param) {
                this.socket.send(param)
            },
            close() {
                console.log("连接关闭")
            },
            openNavi() {
                if (this.socket.readyState == 1) {
                    let obj = {
                        "FunctionName": "naviStatus",
                        "Parameter": {
                            "NaviStatus": this.isTest[0],
                        },
                    }

                    this.send(JSON.stringify(obj));
                    //添加小车
                    this.carIcon(this.carLocaltion);

                    //设置状态
                    this.searchBtnState = 2;
                }

            },
            closeNavi(){
                if (this.socket.readyState == 1) {
                    let obj = {
                        FunctionName: "naviStatus",
                        Parameter: {
                            NaviStatus: this.isTest[1],
                        },
                    }

                    this.send(JSON.stringify(obj));
                    //设置状态
                    this.searchBtnState = -1;
                    this.clearLine()
                }

            },

            reqRoute() {
                if (this.lnglat.length < 2)return;
                if (this.socket.readyState == 1) {
                    let option = {
                        FunctionName: "requestRoute",
                        Parameter: {
                            Strategy: 11,
                            StartPoint: {
                                X: this.lnglat[0].lng,
                                Y: this.lnglat[0].lat
                            },
                            EndPoint: {
                                X: this.lnglat[1].lng,
                                Y: this.lnglat[1].lat
                            },
                            Radius: 0,
                            Height: 0,
                            Width: 0,
                            Weight: 0
                        }
                    }
                    this.send(JSON.stringify(option))
                }
            },
            closeConnect(){
                this.socket.close();
            },
            carIcon(lnglat){
                this.carDiv = document.createElement("div")
                this.carDiv.id = "arrow";
                this.carDiv.innerHTML = "<img src='../../imap_jw/images/arrow.png' style='width: 150px;height: 150px;'>";

                this.carLng = new imapgl.Marker(this.carDiv).setLngLat(lnglat).addTo(this.map);
            },
            getImgSrc() {
                if (this.navLineInfo.Icon)return "../images/route-icon/hud_action_" + this.navLineInfo.Icon + ".png";
            },
            clearLine() {
                if (this.map.getLayer('navLines-style-1')) {
                    this.map.removeLayer('navLines-style-1');
                }
                if (this.map.getSource('route')) {
                    this.map.removeSource('route');
                }
                //清空marker点
                this.lnglat = [];
                this.map["marker_red"] && this.map["marker_red"].remove();
                this.map["marker_blue"] && this.map["marker_blue"].remove();

                if (this.carLng)this.carLng.remove();

                //状态修改
                this.searchBtnState = -1;
            }
            ,
            drawLine: function (lines) {
                if (this.map.getLayer('navLines-style-1')) {
                    this.map.removeLayer('navLines-style-1');
                }
                if (this.map.getSource('route')) {
                    this.map.removeSource('route');
                }
                this.map.addSource('route', {
                    'type': 'geojson',
                    'data': {
                        'type': 'Feature',
                        'properties': {},
                        'geometry': {
                            'type': 'LineString',
                            'coordinates': lines
                        }
                    }
                });
                this.map.addLayer({
                    "id": "navLines-style-1",
                    "type": "line",
                    "source": "route",
                    "layout": {
                        "visibility": "visible",
                        "line-join": "round",
                        "line-cap": "round"
                    },
                    "paint": {
                        "line-translate-anchor": "viewport",
                        "line-width": {
                            "stops": [
                                [
                                    7,
                                    5
                                ],
                                [
                                    18,
                                    20
                                ]
                            ],
                            "base": 1.2
                        },
                        "line-color": "rgba(69,156,80,0.8)"
                    },
                    "interactive": true
                });
            },

        },
        mounted() {
            //初始化地图
            this.initMap();
            //websocket连接
            this.initWebsocket();
        },
        destroyed() {
            this.socket.close();
            this.socket.onclose = this.close
        },
        template: `
				<div id='map' class='map_contaner'></div> 
				<div class='evenDiv'>
				<table  v-if="searchBtnState!=2">
				<tr><td  colspan="5" style="color: #44b79d">请在地图中依次点击标记起点与终点</td></tr>
                   <!-- <tr><td></td><td>起点:</td><td><input id="beginPoint" type="text" placeholder="请在地图中选择起点" readonly="readonly" ></td></tr>
                    <tr><td></td><td>终点:</td><td><input id="endPoint" type="text" placeholder="请再次点击选择终点" readonly="readonly" ></td></tr>-->
                    <tr><td></td><td>车宽:</td><td><input id="carWidth" type="number" step="0.00" placeholder="单位:米"  ></td><td></td></tr>
                    <tr><td></td><td>车高:</td><td><input id="carHeight" type="number" step="0.00" placeholder="单位:米"  ></td><td></td></tr>
                    <tr><td></td><td>车重:</td><td><input id="carWeight" type="number" step="0.00" placeholder="单位:吨" ></td><td></td></tr>
                    <tr><td></td><td>转弯半径:</td><td><input id="carRadius" type="number" step="0.00" placeholder="单位:米" ></td><td></td></tr>
				</table>
				<div href="" class="search-link"  v-if="searchBtnState==2">导航中</div>
				<div href="" @click='clearLine' class="search-link"  v-if="searchBtnState==1">清除线路</div>
				<div @click='reqRoute' class="search-btn" v-if="searchBtnState==0">路径规划</div>
				<div @click='openNavi' class="search-btn" v-if="searchBtnState==1">开始导航</div>
				<div @click='closeNavi' class="search-btn" v-if="searchBtnState==2">退出</div>
			<!--	<div @click='closeConnect' class="search-btn">关闭连接</div>
    CurRoadName: 0,
                    NextRoadName: "",
                    Icon: "",
                    RouteRemainDis: 0,
                    RouteRemainTime: 0,
                    SegRemainDis: 0,
                    CarDirection: 0
-->
				</div>
                <div class="showData"  v-if="searchBtnState==2">
                    <table>
                    <tr><td rowspan="2"><img :src="getImgSrc()" style="height: 100px" alt=""></td><td><span style="font-size: 45px;color: #FFFFFF">{{navLineInfo.SegRemainDis}}</span><span style="color: #FFFFFF;font-size: 20px">米</span></td><td><span style="color: rgb(234 242 245);font-size: 20px">进入</span></td></tr>
                    <tr><td colspan="2"><span style="color: rgb(234 242 245);font-size: 20px">{{navLineInfo.NextRoadName}}</span></td><td></td></tr>
                    <tr><td colspan="3" style="border-top: 1px solid #ffffff;"><span style="color: #FFFFFF;font-size: 20px;" >{{(navLineInfo.RouteRemainDis>1000)?((navLineInfo.RouteRemainDis/1000).toFixed(1))+"公里":navLineInfo.RouteRemainDis+"米"}} 到达目的地</span></td></tr>
                    </table>
                  
                    <div>
<img src="../images/drawable-hdpi/hud_driveway_line.png" alt="">
<img src="../images/drawable-hdpi/default_navi_land_bg_normal.9.png" alt="">
<img src="../images/drawable-hdpi/hud_driveway_line.png" alt="">
<img src="../images/drawable-hdpi/default_navi_land_bg_normal.9.png" alt="">
<img src="../images/drawable-hdpi/hud_driveway_line.png" alt="">
                    </div>
				</div>

				`
    }).mount("#app")
</script>

</html>